# @FileName  :  agent.py
# @Time      :  2025/7/28 22:34
# @Author    :  Ayanami
# @info      :  Agent相关API路由

from typing import Optional, Dict, Any
from fastapi import APIRouter, HTTPException, Query, status
from app.schemas.agent import (
    AgentCreate, AgentUpdate, AgentResponse, AgentDetail,
    AgentListResponse, AgentApprovalRequest
)
from app.crud.agent import agent_crud
from app.models.models import Area

router = APIRouter(tags=["机构管理"])


@router.post("/", response_model=AgentResponse, status_code=status.HTTP_201_CREATED, summary="创建培训机构")
async def create_agent(agent_data: AgentCreate):
    """创建培训机构

    - **name**: 机构名称
    - **credit_code**: 统一社会信用代码（必须唯一）
    - **license_expire**: 执照有效期
    - **business_scope**: 经营范围
    - **legal_person**: 法人姓名
    - **phone**: 联系方式
    - **service_direction**: 服务方向
    - **area_id**: 所属地区ID
    """
    # 检查地区是否存在
    area = await Area.get_or_none(id=agent_data.area_id)
    if not area:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="指定的地区不存在"
        )

    # 检查统一社会信用代码是否已存在
    if await agent_crud.check_credit_code_exists(agent_data.credit_code):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="统一社会信用代码已存在"
        )

    agent = await agent_crud.create(agent_data)
    return agent


@router.get("/", response_model=AgentListResponse, summary="获取培训机构列表")
async def get_agents(
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(20, ge=1, le=100, description="每页数量"),
        search: Optional[str] = Query(None, description="搜索关键词"),
        area_id: Optional[int] = Query(None, description="地区ID"),
        is_approved: Optional[bool] = Query(None, description="审核状态"),
        order_by: str = Query("-created_at", description="排序字段")
):
    """获取培训机构列表"""
    agents, total = await agent_crud.get_list(
        page=page,
        page_size=page_size,
        search=search,
        area_id=area_id,
        is_approved=is_approved,
        order_by=order_by
    )

    # 构造详细信息
    agent_details = []
    for agent in agents:
        agent_dict = agent.__dict__
        agent_dict["area_name"] = agent.area.name if agent.area else None
        agent_details.append(AgentDetail(**agent_dict))

    return AgentListResponse(
        total=total,
        page=page,
        page_size=page_size,
        data=agent_details
    )


@router.get("/{agent_id}", response_model=AgentDetail, summary="获取培训机构详情")
async def get_agent(agent_id: int):
    """获取培训机构详情"""
    agent = await agent_crud.get_by_id(agent_id)
    if not agent:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="培训机构不存在"
        )

    agent_dict = agent.__dict__
    agent_dict["area_name"] = agent.area.name if agent.area else None
    return AgentDetail(**agent_dict)


@router.put("/{agent_id}", response_model=AgentDetail, summary="更新培训机构信息")
async def update_agent(agent_id: int, agent_data: AgentUpdate):
    """更新培训机构信息"""
    # 检查机构是否存在
    existing_agent = await agent_crud.get_by_id(agent_id)
    if not existing_agent:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="培训机构不存在"
        )

    # 如果要更新地区，检查地区是否存在
    if agent_data.area_id is not None:
        area = await Area.get_or_none(id=agent_data.area_id)
        if not area:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="指定的地区不存在"
            )

    # 如果要更新统一社会信用代码，检查是否已存在
    if agent_data.credit_code is not None:
        if await agent_crud.check_credit_code_exists(agent_data.credit_code, exclude_id=agent_id):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="统一社会信用代码已存在"
            )

    agent = await agent_crud.update(agent_id, agent_data)
    agent_dict = agent.__dict__
    agent_dict["area_name"] = agent.area.name if agent.area else None
    return AgentDetail(**agent_dict)


@router.delete("/{agent_id}", status_code=status.HTTP_204_NO_CONTENT, summary="删除培训机构")
async def delete_agent(agent_id: int):
    """删除培训机构"""
    success = await agent_crud.delete(agent_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="培训机构不存在"
        )


@router.patch("/{agent_id}/approval", response_model=AgentDetail, summary="审核培训机构")
async def approve_agent(agent_id: int, approval_data: AgentApprovalRequest):
    """审核培训机构"""
    agent = await agent_crud.approve(agent_id, approval_data.is_approved)
    if not agent:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="培训机构不存在"
        )

    agent_dict = agent.__dict__
    agent_dict["area_name"] = agent.area.name if agent.area else None
    return AgentDetail(**agent_dict)


@router.get("/statistics/overview", response_model=Dict[str, Any], summary="获取培训机构总览信息")
async def get_agent_statistics():
    """获取培训机构统计信息"""
    return await agent_crud.get_statistics()


@router.get("/check-credit-code/{credit_code}", response_model=dict, summary="检查统一社会信用代码")
async def check_credit_code(credit_code: str):
    """检查统一社会信用代码是否可用"""
    exists = await agent_crud.check_credit_code_exists(credit_code)
    return {
        "available": not exists,
        "message": "统一社会信用代码已存在" if exists else "统一社会信用代码可用"
    }